#include "usbcom.h"
#include "globaldata.h"

#define USBCOM_DEVICE0     "/dev/ttyUSB0"  
#define USBCOM_DEVICE1     "/dev/ttyUSB1"  
 
int set_speed(int);
int set_parity(int);
int open_usbcom(int);
int read_usbcom(int ,char*,int);
int write_usbcom(int ,char*,int);

int set_speed(int fd)
{  
  struct termios   options;  

  if  ( tcgetattr( fd,&options)  !=  0) {   
	  perror("SetupSerial get");       
	  return(FALSE);    
  }  

  tcflush(fd, TCIOFLUSH);       

  cfsetispeed(&options, B115200);    
  cfsetospeed(&options, B115200);     

  if (tcsetattr(fd,TCSANOW,&options) != 0)     
  {   
	  perror("SetupSerial set");     
	  return (FALSE);    
  }

  tcflush(fd,TCIOFLUSH);     
}  
/** 
*@brief   设置串口数据位，停止位和效验位 
*@param  fd     类型  int  打开的串口文件句柄 
*/  
int set_parity(int fd)  
{   
    struct termios options;   
    if  ( tcgetattr( fd,&options)  !=  0) {   
        perror("SetupSerial get");       
        return(FALSE);    
    }  

	options.c_cflag &= ~CSIZE;   

	/*设置数据位数*/  
	options.c_cflag |= CS8;  

	/*设置校验位*/
	options.c_cflag &= ~PARENB;   /* Clear parity enable */  
	options.c_iflag &= ~INPCK;     /* Enable parity checking */   

	/* 设置停止位*/    
	options.c_cflag &= ~CSTOPB;    

	/* Set input parity option */   
    tcflush(fd,TCIFLUSH);  
    options.c_cc[VTIME] = 4; /* 设置超时0.4 seconds*/     
    options.c_cc[VMIN] = sizeof(struct _gbdata); /* Update the options and do it NOW */  


    options.c_lflag  &= ~(ICANON | ECHO | ECHOE | ISIG);  /*Input*/  
    options.c_oflag  &= ~OPOST;   /*Output*/  

    if (tcsetattr(fd,TCSANOW,&options) != 0)     
    {   
        perror("SetupSerial set");     
        return (FALSE);    
    }   

    return (TRUE);    
}  
int open_usbcom(int flag)
{
	int ret;
    int fd = open(USBCOM_DEVICE0, flag);  
    if (fd < 0) 
	{  
   		fd = open(USBCOM_DEVICE1, flag);  
		if(fd < 0){
			perror("open");  
			return fd;  
		}
    }  
    printf("Open...\n");  

    if(set_speed(fd) == FALSE)
	{
		printf("Set Speed Error\n");
		close(fd);
		return -1;

	}  

    if (set_parity(fd) == FALSE) 
	{  
        printf("Set Parity Error\n");  
		close(fd);
        return -1;  
    }  

    printf("Start...\n");  

	return fd;
}

int read_usbcom(int fd,char*buf,int sizeof_buf)
{
	int res;
	while(1)
	{
		res = read(fd,buf,sizeof_buf);
		if(res == 0)
		{
			puts("read_usbcom error");
			return res;
		}

		if(res == sizeof(struct _gbdata))
			return res;
	}
}

int write_usbcom(int fd,char*buf,int sizeof_buf)
{
	return write(fd,buf,sizeof_buf);
}
